"""
 Blogger services
 This service relies on Google GData
 
 @author Jean-Lou Dupont
"""
import os
import re

from google.appengine.api import urlfetch

from gdata import service
import gdata.urlfetch

# Use urlfetch instead of httplib
gdata.service.http_request_handler = gdata.urlfetch

from libs.cache import * 

class WBBlogger( object ):
    """
    Blogger
    """

    def __init__(self):
        self.p = re.compile("(.+)post-(.*)$")

    def getPost(self, blog_id, post_id ):
    
        feed = self.getPosts(blog_id)
        if ( feed == 0 ):
            return

        for entry in feed.entry:
            id = entry.id.text
            title = entry.title.text
            content = entry.content.text
            
            if ( self._findPost(entry, post_id, id) ):
                return [title, content]
        
        return [None, None]
 

    def getPosts(self, blogid):
        """
        Returns a feed with all the posts associated with blog identified with 'id'
        """
        return self._getBloggerPosts(blogid)
    

    # since the response is cached, the method name
    # is used to build the cache key
    @cacheResponse(300) 
    def _getBloggerPosts(self, blogid):
        blogger_service = service.GDataService( )
        blogger_service.source  = 'web-bloks/blogger'
        blogger_service.service = 'blogger'
        blogger_service.server  = 'www.blogger.com'

        try:    feed = blogger_service.GetFeed('/feeds/' + blogid + '/posts/default')
        except: feed = 0;
        
        return feed


    def _findPost(self, entry, post_id, search ):
        m = self.p.match( search )
        
        if (m is None):
            return False
        
        rid = m.group(2)
        return ( post_id == rid )
